<template>
  <BasicModal v-bind="$attrs" @register="registerModal" showFooter :title="getTitle" width="50%" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
import { ref, computed, unref } from 'vue';
import { BasicForm, useForm } from '@/components/Form';
import { formSchema } from './index.data';
import { BasicModal, useModalInner } from '@/components/Modal';
import aes from '@/utils/aes';
import { getMenuList } from '@/api/sys/menu';

import { useMessage } from '@/hooks/web/useMessage';

import { saveOrUpdateMenu, info } from '@/api/system/user';

defineOptions({ name: 'Modal' });

const { createMessage: msg } = useMessage();

const emit = defineEmits(['success', 'register']);

const isUpdate = ref(true);

const [registerForm, { resetFields, setFieldsValue, updateSchema, validate, setProps }] = useForm(
  {
    labelWidth: 140,
    schemas: formSchema,
    showActionButtonGroup: false,
    baseColProps: { lg: 12, md: 24 },
  },
);

const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  resetFields();
  setProps({ disabled: data.isLook });
  setModalProps({ confirmLoading: false });
  isUpdate.value = !!data?.isUpdate;
  let res = await info(data.record.id)

  if (unref(isUpdate)) {
    setFieldsValue({
      ...res.data,
    });
  }
  const treeData = await getMenuList();
  updateSchema({
    field: 'parentId',
    componentProps: { treeData },
  });
});

const getTitle = computed(() => (!unref(isUpdate) ? '新增用户' : '编辑用户'));

async function handleSubmit() {
  try {
    const values = await validate();
    setModalProps({ confirmLoading: true });
    values.password = aes.encrypt(values.password);
    const res = await saveOrUpdateMenu(values, !!values.id);
    if (res.isSucceed) {
      msg.success('操作成功');
      closeModal();
      emit('success');
    }
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
</script>
